//
//  ForgotPassword_VC.m
//  SpendMoney
//
//  Created by  lixinxin on 16/12/28.
//  Copyright © 2016年  lixinxin. All rights reserved.
//

#import "ForgotPassword_VC.h"
#import "CRNCountDownButton.h"
#import "iPhoneType.h"
#import "LoginPublic.h"
#import "AppDelegate.h"

#define kPhoneTag 200
#define kPasswordTag 201
#define kConfirmPasswordTag 202

@interface ForgotPassword_VC ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *phone_Vi;
@property (weak, nonatomic) IBOutlet UIView *verificationCode_Vi;
@property (weak, nonatomic) IBOutlet UIView *password_Vi;

@property (weak, nonatomic) IBOutlet UITextField *phone_TextField;

@property (weak, nonatomic) IBOutlet UITextField *verificationCode_TextField;
@property (weak, nonatomic) IBOutlet UITextField *password_TextField;

@property (weak, nonatomic) IBOutlet CRNCountDownButton *verificationCode_Button;

@property (weak, nonatomic) IBOutlet UIButton *confirmButton;


@end

@implementation ForgotPassword_VC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
//    self.navigationItem.title = @"忘记密码";
    
    [self initMethod];
    
    self.phone_TextField.delegate = self;
    self.phone_TextField.tag = kPhoneTag;
    
    self.password_TextField.delegate = self;
    self.password_TextField.tag = kPasswordTag;
    self.password_TextField.returnKeyType = UIReturnKeyJoin;
    
    [self.verificationCode_Button setBackgroundColor:MAIN_COLOR];
    [self.confirmButton setBackgroundColor:MAIN_COLOR];
}

- (void)initMethod {
    
//    [self setBorMethod:self.phone_Vi];
    [self setBorMethod:self.password_Vi];
    [self setBorMethod:self.verificationCode_Vi];
    
    if (self.phoneStr) {
        self.phone_TextField.text = [NSString stringWithFormat:@"%@****%@", [self.phoneStr substringToIndex:3], [self.phoneStr substringFromIndex:7]];
    }
}


- (void)setBorMethod:(UIView *)vi {
    
    vi.layer.borderWidth = 1;
    vi.layer.borderColor = UIColorFromRGB(0xe9e9e9).CGColor;
    vi.layer.cornerRadius = 4;
}

#pragma mark - 获取验证码
- (IBAction)verificationCodeAction:(CRNCountDownButton *)sender {
    

    if (![EMAILANDPHONE validateMobile:self.phoneStr]) {
        [[Toast makeText:@"手机号输入不正确"] show];
    } else {
        
        [self.phone_TextField resignFirstResponder];  // 取消第一响应
        
        if ([self.verificationCode_Button.titleLabel.text isEqualToString:@"重新获取"] || [self.verificationCode_Button.titleLabel.text isEqualToString:@"获取验证码"]) {
            
            
            sender.enabled = NO;
           
            [sender didFinished:^NSString *(CRNCountDownButton *countDownButton, int second) {
                countDownButton.enabled = YES;
                return @"重新获取";
            }];
            NSDictionary *param = @{@"Mobile":self.phoneStr, @"FunctionType":[NSString stringWithFormat:@"%@", _tagStr], @"ProductType":@1};

            [Network link:kSendVcode
                                      parameters:param
                                       outOfTime:0.f
                                        callback:^(Network *response) {
                                            if (response.responCode==1) {
                                                [self alertMessage:response.dataDic[@"message"] title:nil forAnimation:@(1.f)];
                                                
                                                
                                                [self.verificationCode_TextField becomeFirstResponder];
                                                
                                                sender.enabled = NO;
                                                [sender startWithSecond:60];
                                                [sender didChange:^NSString *(CRNCountDownButton *countDownButton,int second) {
                                                    NSString *title = [NSString stringWithFormat:@"剩余%d秒",second];
                                                    return title;
                                                }];
                                                [sender didFinished:^NSString *(CRNCountDownButton *countDownButton, int second) {
                                                    countDownButton.enabled = YES;
                                                    return @"重新获取";
                                                }];
                                            } else {
                                                [sender stop];
                                                sender.enabled = YES;
                                                if (response.dataDic[@"message"]) {
                                                    [self alertMessage:response.dataDic[@"message"] title:@"提示" forAnimation:@(2.f)];

                                                }
                                            }
                                        }];
        }
    
    
    }


}
#pragma mark - 字数限制
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容

    if (textField.tag == kPhoneTag) {  // 手机号
        if (toBeString.length > 11) {
            return NO;
        }
        return YES;
    }
    // 密码和重复密码
    if (toBeString.length > 16) {
        return NO;
    }
    return YES;
}

#pragma mark - textFieldShould
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    if (textField.tag == kPasswordTag) {
        // 登录事件
        [self determineMethod];

    }
    
    return YES;
}

#pragma mark - 点击确认按钮
- (IBAction)confirmButtonAction:(UIButton *)sender {
    [self determineMethod];
}

- (void)determineMethod {

    [self.view endEditing:YES];

    if (self.phone_TextField.text.length == 0) {
        [[Toast makeText:@"手机号不能为空"] show];
        return;
    }
    if (self.verificationCode_TextField.text.length == 0) {
        [[Toast makeText:@"验证码不能为空"] show];
        return;
    }
    if (self.password_TextField.text.length == 0) {
        [[Toast makeText:@"密码不能为空"] show];
        return;
    }
    
    if (self.password_TextField.text.length < 6 || self.password_TextField.text.length > 16) {
        
        [[Toast makeText:@"请您输入6-16位数密码"] show];

        return;
    }
    
    NSString *iOSVersion = [iPhoneType phoneVersionMethod];
    NSString* iPhoneT = [iPhoneType iphoneTypeMethod];//方法在下面
    
    NSString *macStr = @"iOS";
    if ([MACID SSIDInfo]) {
        NSDictionary *macidDict = [MACID SSIDInfo];
        macStr = macidDict[@"BSSID"];
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:self.phoneStr forKey:@"UserName"];
    [params setValue:self.phoneStr forKey:@"Mobile"];

    [params setValue:[sharBaseTool decrypt:User_ID] forKey:@"UserId"];
    [params setValue:@"iOS" forKey:@"Channel"];

    [params setValue:self.password_TextField.text forKey:@"Password"];
    [params setValue:self.verificationCode_TextField.text forKey:@"Vcode"];
    [params setValue:@2 forKey:@"Source"];
    [params setValue:@1 forKey:@"RegisterSource"];
    
    if ([_tagStr isEqualToString:@"0"]) {
        [params setValue:@1 forKey:@"RegisterSource"]; // 注册来源0-喜花钱,1-周周发薪贷
    }
    
    [params setValue:[SpendMoneyKeyChain readUUIDFromKeyChain] forKey:@"DeviceId"];
    [params setValue:macStr forKey:@"MACAddress"];
    [params setValue:iPhoneT forKey:@"PhoneModel"];
    [params setValue:@"iPhone" forKey:@"PhoneBrand"];
    [params setValue:iOSVersion forKey:@"PhoneSystemModel"];

    [params setValue:[cSysPlist objectForKey:kLongitude] forKey:@"Longitude"]; // 经度
    [params setValue:[cSysPlist objectForKey:kLatitude] forKey:@"Latitude"];   // 维度
    [params setValue:_tagStr forKey:@"FunctionType"];
    
    self.confirmButton.enabled = NO;
    [Network link:kAddAppUserOrfindPassword
                              parameters:params
                               outOfTime:0.f
                                callback:^(Network *response) {
                                    if (response.responCode==1) {
                                    
                                        if ([@"1" isEqualToString:_tagStr]) {
                                            [[Toast makeText:response.dataDic[@"message"]] show];
                                        } else {
                                            // 友盟统计
                                            [ZZDHStatRegisteredEvent mdf_UMClickStatistical];
                                        }
                                        
//                                        [self.navigationController popViewControllerAnimated:YES];
                                        [self registCompleteAutoLoginMethod];
                                        
                                    } else {
                                        self.confirmButton.enabled = YES;

                                        [self alertMessage:response.dataDic[@"message"] title:@"提示" forAnimation:@(2.f)];
                                    }
                                }];
    
}


#pragma mark - 注册完成，返回后自动登录
- (void)registCompleteAutoLoginMethod {

//    if ([@"0" isEqualToString:_tagStr]) {  // 0-注册，1-忘记密码

        [self loginMethod:self.phoneStr pwdStr:self.password_TextField.text];
//    }
    
}

#pragma mark - 登录
- (IBAction)loginAction:(UIButton *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 忘记密码
- (IBAction)ForgotPasswordAction:(UIButton *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];

}

#pragma mark - 登录
- (void)loginMethod:(NSString *)mobStr pwdStr:(NSString *)pwdStr {
    
    [LoginPublic loginMethod:^(NSDictionary *loginDict, BOOL b, NSString *msg) {
        if (b) {
            // 登录成功，
            AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            //跳转到首页
            if (self.b) {
                [self dismissViewControllerAnimated:YES completion:^{
                    [app setupRootViewController];
                }];
            } else {
                [app setupRootViewController];
            }
            
            // 登录成功，
            ShareBorrowPublic_VC.afnetwordB = NO;
            
            
        } else {
            
            if (msg) {
                [self alertMessage:msg title:@"提示" forAnimation:nil];
                
            }
            
        }
        
    } mobStr:mobStr pwdStr:pwdStr];
    
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    
//    self.navigationController.navigationBar.translucent = YES;
//    
//    UIImage *image = [UIImage imageNamed:@"transparent.png"];
//    [self.navigationController.navigationBar setBackgroundImage:image
//                                                  forBarMetrics:UIBarMetricsDefault];//代码1
//    [self.navigationController.navigationBar setShadowImage:image];//代码2
    
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    self.tabBarController.tabBar.hidden = NO;
    //    self.navigationController.navigationBarHidden = NO;  // 显示导航栏
//    self.navigationController.navigationBar.translucent = NO;
//    
//    UIImage *image = [UIImage imageNamed:@"transparent.png"];
//    [self.navigationController.navigationBar setBackgroundImage:image
//                                                  forBarMetrics:UIBarMetricsCompact];//代码1
    
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
